package com.mhg.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 实现Callable接口创建线程
 */
public class CountThread implements Callable {
    /**
     * 入口程序
     * @param args
     */
    public static void main(String[] args) {
        //创建线程
        CountThread countThread = new CountThread();
        FutureTask futureTask = new FutureTask(countThread);
        Thread t1 = new Thread(futureTask);
        Thread t2 = new Thread(futureTask);
        Thread t3 = new Thread(futureTask);
        //启动线程
        t1.start();
        t2.start();
        t3.start();

        try{
            Object sum = futureTask.get();
            System.out.println("总和为--："+ sum);
        }catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    /**
     * 线程的具体执行逻辑
     * @return
     * @throws Exception
     */
    @Override
    public Object call() throws Exception {
        //实现求十万以内的所有偶数的和
        int sum = 0;
        synchronized (CountThread.class) {
            for (int i = 0; i <= 100000; i++) {
                if (i % 2 == 0) {
                    if (i == 99998) {
                        //休眠5秒
                        Thread.sleep(5000);
                    }
                    System.out.println(i);
                    sum += i;
                }
            }
        }
        return sum;
    }
}
